﻿using Aliyun.OSS;

namespace AuSys.Services.App.FileStorage.Specific
{
    public class AliyunOssStorage : IFileStorage
    {
        private readonly AliyunOssStorageConfig _config;
        private readonly Lazy<OssClient> _ossClient;
        public StorageProvideType ProvideType => StorageProvideType.Redirect;
        public AliyunOssStorage(AliyunOssStorageConfig config)
        {
            _config = config;
            _ossClient = new Lazy<OssClient>(() => new OssClient(
                _config.EndPoint, _config.AccessKeyId, _config.AccessKeySecret));
        }
        public bool Save(Stream s, string pathName, out string? errmsg)
        {
            try
            {
                _ossClient.Value.PutObject(_config.BucketName, pathName, s);
            }
            catch(Exception ex)
            {
                errmsg = ex.Message;
                return false;
            }
            errmsg = null;
            return true;
        }
        public bool Delete(string pathName, out string? errmsg)
        {
            try
            {
                _ossClient.Value.DeleteObject(_config.BucketName, pathName);
            }
            catch(Exception ex)
            {
                errmsg = ex.Message;
                return false;
            }
            errmsg = null;
            return true;
        }
        public string FullUrl(string pathName)
        {
            return $"{_config.DomainName}/{pathName}";
        }
        public Stream? Read(string pathName)
        {
            var obj = _ossClient.Value.GetObject(_config.BucketName, pathName);
            return obj.ResponseStream;
        }
    }

    public class AliyunOssStorageConfig
    {
        public string? EndPoint { get; set; }
        public string? BucketName { get; set; }
        public string? AccessKeyId { get; set; }
        public string? AccessKeySecret { get; set; }
        public string? DomainName { get; set; }
    }
}
